<template>
  <div class="refine_message">
    <h2 class="titleblue">消息列表</h2>
    <div class="contant">
      <div class="plan-operate">
        <div @click="readAll" class="create">全部置为已读</div>
        <div @click="deleteAll" class="create">清空所有消息</div>
        <div style="flex:1;"></div>
        <el-select @change="searchMsg" class='_select-width-200' v-model="messageType" clearable style="margin-right:20px" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
        <el-input prefix-icon="el-icon-search" placeholder="搜索任务" v-model="kw" clearable
                  class="plansearch" @change="searchMsg">
          <template slot="append">搜索</template>
        </el-input>
      </div>
      <div class="main">
        <el-row v-for='(item,index) in messages' :key='index' class="list-row" @click.native='readMsg(item)'>
          <el-col :span="2" :style='{color:item.color}'>{{item.messageType}}
            <div class="grid-content bg-purple"></div>
          </el-col>
          <el-col :span="14" style="cursor: pointer;">
            <a :title='item.content' :style='{color:item.color}'>{{item.content.slice(0,30)}}</a>
            <div class="grid-content bg-purple"></div>
          </el-col>
          <el-col :span="3" style="font-size: 12px;cursor:pointer;text-align: center;height:50px;">
            <div class="grid-content bg-purple info-btn" v-on:click.stop="processTask(item)" v-if="item.routerName">立即处理</div>
          </el-col>

          <el-col :span="5" @click='readMsg(item)'>{{$m(item.createTime).format('YYYY-MM-DD HH:mm:ss')}}
            <div class="grid-content bg-purple el-icon-close" v-on:click.stop="deleteNews(item.id)"
                 style="margin-left:10px;font-size: 12px;cursor:pointer"></div>
          </el-col>
        </el-row>

        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          layout="total, prev, pager, next"
          :total="dataCount"
          background>
        </el-pagination>

      </div>
    </div>
  </div>
</template>

<script>
  import dictService from '@/services/DictionaryService.js'
  import messageService from '@/services/MessageService.js'
  import taskService from '@/services/TaskService.js'
  import * as orgService from '@/services/OrganizationService'

  export default {
    data() {
      return {
        options: [],
        kw: '',
        currentPage: 1,
        dataCount: 0,
        newMsg: false,
        messageType: '',
        messages: [],
        searchOrgs: []
      }
    },
    // watch: {
    //   messages: {
    //     deep: true,
    //     handler (newVal, oldVal) {
    //       console.log('changed:::', newVal)
    //     }
    //   }
    // },
    mounted() {
      this.getOptions()
      this.getMsg()
    },
    methods: {
      getOptions() {
        dictService.find('XXLB').then(data => {
          // console.log('data::', data)
          this.options = data
        })
        orgService.findAll().then(async res => {
          await res.data.sort((a, b) => {
            if (a.businessOrg < b.businessOrg) {
              return -1
            }
            if (a.businessOrg > b.businessOrg) {
              return 1
            }
            return 0
          })
          this.searchOrgs = res.data
        })
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getMsg()
      },
      searchMsg() {
        this.currentPage = 1
        this.getMsg()
      },
      async getMsg() {
        let userId = this.$profile.id
        let query = 'deleteFlag==false;userId=_=' + userId + ';orgId=_=' + this.$profile.organiza.id + ';';
        if (this.messageType) {
          query += 'messageType==' + this.messageType + ';'
        }
        if (this.kw) {
          query += 'content=like=' + this.kw
        }
        query += '&sort=id,desc'
        // console.log('xxxx', userId, this.messageType, this.kw)
        let ret = await messageService.ps(this.currentPage - 1, query)
        this.newMsg = false
        let messages = ret.data

        let taskIdAry = [];
        messages.forEach(msg => {
          msg.color = (msg.status === 1 ? 'red' : 'black')
          taskIdAry.push(msg.taskId)
        })

        if (taskIdAry.length) {
          let taskQuery = 'id=in=' + taskIdAry.join(',')
          let taskRet = await taskService.ps(0, taskQuery, 10)
          // console.log('task ary:', taskAry)
          taskRet.data.forEach(t => {
            let msg = messages.find(m => m.taskId === t.id)
            if (t.taskState === 0 && this.$profile.organiza.businessOrg === 5) {
              // 派发
              msg.routerName = 'SendTask'
            } else if ((t.taskState === 1 || t.taskState === 2) && this.$profile.organiza.id === t.orgId) {
              // 派发
              msg.routerName = 'SendTask'
            } else if (t.taskState === 8) {
              if (t.superviseFlag) {
                // 督查
                msg.routerName = 'supDetail'
              } else {
                // 评价
                msg.routerName = 'supDetail'
              }
            } else if (t.taskState === 9) {
              // 收任务 不需要跳页
              msg.routerName = 'receive'
            }
            msg.task = t
          })
        }

        this.messages = messages
        this.dataCount = ret.dataCount

      },
      async readMsg(item) {
        if (item.status === 1) {
          await messageService.setReadStatus(item.id, 1)
        }
        this.searchMsg()
        if (item.taskType == '计划任务') {
          // this.$alert('显示计划任务详情')
          this.$router.push({name: 'CreateScheduleTask', params: {searchOrgs: this.searchOrgs, data: item.task, type: 'view'}})
            // this.$router.push({
            //   path: '/index/task/taskinfop',
            //   params: {
            //     id: item.taskId
            //   }
            // })
        } else {
          // this.$alert('显示任务详情')
          this.$router.push({name: 'CreateEverydayTask', params: {data: item.task, type: 'view'}})
            // this.$router.push({
            //   name: '/everydat-task/create',
            //   query: {
            //     id: item.taskId
            //   }
            // })
          }
      },
      // 设置全部消息为已读
      readAll() {
        messageService.setReadStatus(-1, 1).then(res => {
          this.$alert('消息已全部已读')
          this.searchMsg()
        })
      },
      deleteNews(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          messageService.delete(id).then(res => {
            this.$alert("删除成功", '提示');
            this.getMsg()
          })
        })
      },
      deleteAll() {
        this.$confirm('此操作将清除全部消息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          messageService.delete(-1).then(res => {
            this.$alert('消息已清空')
            this.getMsg()
          })
        })
      },
      processTask(item){

        if(item.routerName == 'supDetail'){ // 督察
          this.$router.push({name: item.routerName, params: {data: item.task, pageType: 'supervision', detailType: item.task.superviseFlag}})
        } else if (item.routerName == 'SendTask'){ // 派发
          this.$router.push({name: item.routerName, params: {data: item.task}})
        }else if (item.routerName == 'receive'){ // 收任务
          this.$confirm('立即接收任务则不可退回', '提示', {
            confirmButtonText: '接收',
            cancelButtonText: '暂不',
          }).then(() => {
            taskService.update({id: item.task.id}, 5).then(res => {
              if (res) {
                this.$message({
                  type: 'success',
                  message: '接收成功'
                })
              }
            })
          })

        }
      }
    }
  }
</script>

<style lang="scss" scoped>

  .refine_message {
    width: 100%;

    .plan-operate {
      display: flex;
      align-items: center;
    }

    .list-row {
      display:flex;
      align-items:center;
      border-bottom:solid 1px #ccc;
      color: #666;
      font-size: 14px;
      cursor:pointer;
    }

    .info-btn{
      width: 90px;
      height: 30px;
      background-color: #0062cd;
      border-radius: 4px;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 30px;
      cursor: pointer;
      margin-top: 10px;
    }
  }
</style>
